//
//  WBPictureView.swift
//  GitWeibo
//
//  Created by 胡金东 on 2017/6/6.
//  Copyright © 2017年 胡金东. All rights reserved.
//

import UIKit

class WBPictureView: UIView {
    
    var viewModel:WBStatusViewModel?{
        didSet{
            calcViewSize()
            urls = viewModel?.picURLs
        }
    }
    
    func calcViewSize()  {
        /// - 单图
        if viewModel?.picURLs?.count == 1 {
            let viewSize = viewModel?.pictureSize ?? CGSize()
            
            /// - 获取第0个图像视图
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: 0, width: viewSize.width, height: viewSize.height)
        }else{
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: 0, width: WBStatusEveryOnePictureWidth, height: WBStatusEveryOnePictureWidth)
            
        }
        
        
        
         /// - 设置配图高度
         pictureHeight.constant = viewModel?.pictureSize.height ?? 0
        
    }
    
    /// - 配图的数组
    var urls : [WBPictureModel]?{
        didSet{
            /// - 隐藏所有的imageView （刚开始创建是有多的）
            for imgV in subviews {
                imgV.isHidden = true
            }
            /// - 遍历 urls 数组 ，顺序设置图像
            var index = 0
            for url in urls ?? [] {
            /// - 获得对应索引的imageView
            let IV = subviews[index] as! UIImageView
            
             /// - 4张图像处理
                if index == 1 && urls?.count == 4 {
                    index += 1
                }
                
            /// - 设置图像
            IV.setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
            /// - 显示图像
            IV.isHidden = false
            
            index += 1
            }
        }
    }
    

    /// - 配图的高度
   @IBOutlet var pictureHeight: NSLayoutConstraint!
    
    override func awakeFromNib() {
        setUpUI()
    }

}

extension WBPictureView {
    func setUpUI()  {
        /// - 显示父类背景颜色，（转发和原创背景色不一样）
        backgroundColor = superview?.backgroundColor

        /// - 超出边界的内容不显示
        clipsToBounds = true
        
        let count = 3
        let rect = CGRect(x: 0, y: 0, width: WBStatusEveryOnePictureWidth, height: WBStatusEveryOnePictureWidth)
        
        for i in 0..<count * count {
            let imageView = UIImageView()
            /// - 设置contentMode 图片不变形
            imageView.contentMode = .scaleAspectFill
            imageView.clipsToBounds = true
          
            /// - 列 -> X
            let col = CGFloat(i % count)
            /// - 行 -> Y
            let row = CGFloat(i / count)
            
            let offsetX = col * (WBStatusEveryOnePictureWidth + WBStatusPictureViewInnerMargin)
            let offsetY = row * (WBStatusEveryOnePictureWidth + WBStatusPictureViewInnerMargin)
            
            imageView.frame = rect.offsetBy(dx: offsetX, dy: offsetY)
            
            addSubview(imageView)
            
            
            
            
        }
        
        
        
    }
}
